# routers/user.py
import hashlib

import jwt
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from langserve import RemoteRunnable
from sqlalchemy.orm import Session

from core.crud import create_user, user_detail_by_username
from core.database import get_db
from core.schemas import UserCreate, ResponseModel, UserLogin

router = APIRouter(
    prefix="/user",
    tags=["user"],
    responses={404: {"description": "Not found"}},
)

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="user/login")


def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, "demo-key", algorithms=["HS256"])
        username: str = payload.get("username")
        if username is None:
            raise credentials_exception
    except jwt.ExpiredSignatureError:
        raise credentials_exception
    return username


@router.post("/register", response_model=ResponseModel)
async def user_register(user: UserCreate, db: Session = Depends(get_db)):
    db_user = create_user(db, username=user.username, password=user.password)
    return {"data": db_user, "code": "success", "message": "User created successfully"}


# @router.post("/login", response_model=ResponseModel)
# async def login(user: UserLogin, db: Session = Depends(get_db)):
#     db_user = authenticate_user(db, username=user.username, password=user.password)
#     if db_user:
#         return {"data": db_user, "code": "success", "message": "User logged in successfully"}
#     else:
#         raise HTTPException(status_code=400, detail="Invalid username or password")
@router.post("/login")
async def user_login(user_login: UserLogin, db: Session = Depends(get_db)):
    user = user_detail_by_username(db, user_login.username)
    if not user:
        return ResponseModel(data=None, code="404", message="User does not exist")
    if hashlib.md5(user_login.password.encode()).hexdigest() != user.password:
        return ResponseModel(data=None, code="401", message="Password error")

    payload = {
        "user_id": user.user_id,
        "username": user.username  # Add the username to the JWT token
    }
    return ResponseModel(data={"token": jwt.encode(payload, "demo-key", algorithm="HS256"), "user_id": user.user_id}, code="200",
                         message="success")


# @router.post("/invoke", response_model=ResponseModel)
# async def invoke_endpoint(data: dict, current_user: str = Depends(get_current_user)):
#     # You can use current_user if you want to restrict access further
#     response = invoke(data)
#     return {"data": response, "code": "success", "message": "User created successfully"}
